<?php

namespace App\Helper;

use App\ATrait\Single;
use App\Models\V1\ConfigBusiness;
use Exception;
use Illuminate\Support\Facades\Cache;

class Config
{

    use Single;


    protected string $keyPrefix;


    public function __construct()
    {
        $this->keyPrefix = 'CONFIG:';
    }


    /**
     * 新建键名
     *
     * @param $key
     * @param $value
     * @param string $desc
     * @param int $ttl
     * @return bool
     * @throws Exception
     */
    public function Set($key, $value, string $desc = "", int $ttl = 0): bool
    {

        try {
            $isExists = ConfigBusiness::query()->where("key", $key)->exists();
            if (!$isExists) {
               ConfigBusiness::query()->create([
                    "key" => $key,
                    "value" => $value ?? "",
                    "desc" => $desc,
                    "expires_in" => $ttl,
                ]);
            } else {
               ConfigBusiness::query()->where("key", $key)->update([
                    "value" => $value ?? "",
                    "expires_in" => $ttl,
                ]);
            }
            if (empty($ttl)) {
                Cache::put($this->keyPrefix . $key, $value);
            } else {
                Cache::put($this->keyPrefix . $key, $value, $ttl);
            }
        } catch (Exception $ex) {
            throw new Exception("配置项添加失败", 500000);
        }

        return true;

    }


    /**
     * 获取键值
     *
     * @param $key
     * @param string $default
     * @return mixed
     */
    public function Get($key, string $default = ""): mixed
    {

        return Cache::rememberForever($this->keyPrefix . $key, function () use ($key, $default) {
            $info =ConfigBusiness::query()->where("key", $key)->first();
            if ($info) {
                return $info->value;
            } else {
                return $default;
            }
        });

    }

}
